/**
 * 102. 二叉树的层序遍历
 * https://leetcode-cn.com/problems/binary-tree-level-order-traversal/
 */
const { createTreeNode, displayNestedArray } = require('../../libs/public');

/**
 * @param {TreeNode} root
 * @return {number[][]}
 */
function levelOrder(root) {
  if (!root) return [];
  const stack = [root];
  const result = [];
  while (stack.length) {
    result.push(stack.map((node) => node.val));
    const { length } = stack;
    for (let i = 0; i < length; i += 1) {
      const node = stack.shift();
      if (node.left) stack.push(node.left);
      if (node.right) stack.push(node.right);
    }
  }
  return result;
}

console.log(displayNestedArray(levelOrder(createTreeNode([3, 9, 20, null, null, 15, 7]))) === '[[3],[9,20],[15,7]]');
console.log(displayNestedArray(levelOrder(createTreeNode([1]))) === '[[1]]');
console.log(displayNestedArray(levelOrder(createTreeNode([]))) === '[]');
